package com.muyan.sys.common.utils;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import com.muyan.sys.common.utils.spring.SpringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Locale;

/**
 * 获取i18n资源文件
 * 
 * @author muyan
 */
public class MessageUtils
{
    /**
     * 根据消息键和参数 获取消息 委托给spring messageSource
     *
     * @param code 消息键
     * @param args 参数
     * @return 获取国际化翻译值
     */
    public static String message(String code, Object... args)
    {


        MessageSource messageSource = SpringUtils.getBean(MessageSource.class);


        Locale locale = LocaleContextHolder.getLocale();

        return messageSource.getMessage(code, args, locale);
    }
    /**
     * 切换语言
     *
     * @param
     * @param
     * @return 获取国际化翻译值
     */
    public static void changeMessage()
    {

        try {

            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String language="";
            if (request != null) {
                language = request.getHeader("Custom-Lanuage-Type");

            }
            Locale locale =  getMessage(language);
            if(locale!=null){
                LocaleContextHolder.setLocale(locale);
            }

        }catch (Exception e){

        }
    }
    /**
     * 切换语言
     *
     * @param
     * @param
     * @return 获取国际化翻译值
     */
    public static Locale getMessage(String language)
    {

        if("zh".equals(language)){
            return Locale.SIMPLIFIED_CHINESE;
        }else if("en".equals(language)){
            return Locale.US;
        }else{
            return Locale.SIMPLIFIED_CHINESE;
        }
    }
}
